﻿using ServiceStack;
using ServiceStack.Host;
using ServiceStack.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Ymatou.PerfMonitorClient;
using YmtAuth.AppService.JavaService;
using YmtSystem.CrossCutting;
using ResetService = ServiceStack.Service;

namespace YmtAuth.Web.Service
{
    public class InterceptServiceStackService : ResetService
    {

        public override void Dispose()
        {
            base.Dispose();
        }

    }



    public class InterceptServiceStackService<TRequest> : ServiceRunner<TRequest>
    {
        public override void BeforeEachRequest(IRequest requestContext, TRequest request)
        {
            base.BeforeEachRequest(requestContext, request);
        }

        /// <summary>
        /// 对于写操作，全部调用JAVA服务的接口，其他操作不拦截
        /// </summary>
        /// <param name="request"></param>
        /// <param name="instance"></param>
        /// <param name="requestDto"></param>
        /// <returns></returns>
        public override object Execute(IRequest requestContext, object instance, TRequest requestDto)
        {
            var writeRespFromJavaService = RequestUserService.transferWriteRequestToJavaService(requestContext.Dto
                      , requestContext.OperationName
                      , requestContext.RawUrl
                      , requestContext.GetHttpMethodOverride());

            if (writeRespFromJavaService != null) return writeRespFromJavaService;

            return base.Execute(requestContext, instance, requestDto);
        }


        public override object OnAfterExecute(IRequest requestContext, object response)
        {
            var respObj = base.OnAfterExecute(requestContext, response);
            try
            {
                Task.Factory.StartNew(() =>
                {
                    RequestUserService.sendWriteRequest(requestContext.Dto
                      , respObj
                      , requestContext.OperationName
                      , requestContext.RawUrl
                      , requestContext.GetHttpMethodOverride());
                });
            }
            catch (Exception ex)
            {
                using (MethodMonitor.New("AUTH_DoubleWrite_Error")) ;
                YmatouLoggingService.Error("认证服务双写失败,requestObj:{0}".Fmt(requestContext.Dto.ToJson()), ex);
            }
            return respObj;
        }

        public InterceptServiceStackService(IAppHost appHost, ActionContext actionContext)
            : base(appHost, actionContext)
        {
        }
    }


}